package com.fsh.anime.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsh.anime.mapper.ArticleMapper;
import com.fsh.anime.mapper.CommentMapper;
import com.fsh.anime.mapper.FanjuMapper;
import com.fsh.anime.mapper.UserMapper;
import com.fsh.anime.model.dtos.ReplyCommentDto;
import com.fsh.anime.model.dtos.SaveCommentDto;
import com.fsh.anime.model.pojos.Article;
import com.fsh.anime.model.pojos.Comment;
import com.fsh.anime.model.pojos.Fanju;
import com.fsh.anime.model.pojos.User;
import com.fsh.anime.model.vos.CommentAllVo;
import com.fsh.anime.model.vos.CommentVo;
import com.fsh.anime.model.vos.Result;
import com.fsh.anime.service.CommentService;
import com.fsh.anime.utils.BaseContext;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private FanjuMapper fanjuMapper;

    /**
     * 新增评论
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveComment(SaveCommentDto dto) {
        //更新文章的评论数。多线程.  线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
                5, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(2),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        FutureTask<Boolean> task=new FutureTask<>(() -> {
            if (dto.getArticleId()>10000000000000L){
                //文章id
                Article article = articleMapper.selectById(dto.getArticleId());
                int comments = articleMapper.update(article, new UpdateWrapper<Article>()
                        .eq("id",article.getId())
                        .set("comments", article.getComments() + 1));
                return comments>0;
            }else{
                //番剧id
                Fanju fanju = fanjuMapper.selectById(dto.getArticleId());
                int comments = fanjuMapper.update(fanju, new UpdateWrapper<Fanju>()
                        .eq("id",fanju.getId())
                        .set("comments", fanju.getComments() + 1));
                return comments>0;
            }
        });

        threadPoolExecutor.submit(task);

        Comment comment=new Comment();
        BeanUtils.copyProperties(dto,comment);
        //查询当前用户信息
        User user = userMapper.selectById(BaseContext.getCurrentId());
        comment.setUserId(user.getId().longValue());
        comment.setName(user.getName());
        //插入到数据库中
        int insert = commentMapper.insert(comment);

//        log.info("CommentServiceImpl.saveComment.comment:{}",comment);
        try {
            if (insert>0 && task.get()){
                return Result.success("评论成功");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return Result.success("评论失败");
    }

    /**
     * 获取评论：一级和二级评论
     *
     * @param articleId
     */
    @Override
    public Result getComment(String articleId) {
        log.info("CommentServiceImpl.saveComment.comment:{}",articleId);
        // todo 这里直接全部查出来，应该是分页查询
        if (StringUtils.isNotBlank(articleId)){
            //这里是所有的评论
            List<Comment> comments = commentMapper.selectList(new QueryWrapper<Comment>().eq("article_id", articleId).orderByDesc("create_time"));
            List<CommentAllVo> commentAllVoList=new ArrayList<>();

            //所有的一级评论
            List<Comment> firstCommentList = comments.stream().filter(comment -> comment.getState() == 1).collect(Collectors.toList());
            //所有的二级评论
            List<Comment> secondCommentList = comments.stream().filter(comment -> comment.getState() == 2).collect(Collectors.toList());
            //遍历一级评论
            for (Comment firstCommnet : firstCommentList) {
                CommentAllVo commentAllVo=new CommentAllVo();
                CommentVo commentVo=new CommentVo();
                BeanUtils.copyProperties(firstCommnet,commentVo);
                commentVo.setHuifu_div(false);
                commentAllVo.setCommentVo(commentVo);

                List<CommentVo> commentVoList1=new ArrayList<>();
                //遍历二级评论
                for (Comment secondComment : secondCommentList) {
                    if (secondComment.getParentId()==firstCommnet.getId()){
                        CommentVo commentVo1=new CommentVo();
                        BeanUtils.copyProperties(secondComment,commentVo1);
                        commentVo1.setHuifu_div(false);
                        commentVoList1.add(commentVo1);
                    }
                }
                commentAllVo.setCommentVoList(commentVoList1);
                commentAllVoList.add(commentAllVo);
            }
            return Result.success(commentAllVoList);
        }
        return Result.error("评论加载失败");
    }

    /**
     * 回复评论
     */
    @Override
    public Result replyComment(ReplyCommentDto dto) {
        Comment comment=new Comment();
        BeanUtils.copyProperties(dto,comment);
        //查询当前用户信息
        User user = userMapper.selectById(BaseContext.getCurrentId());
        comment.setUserId(user.getId().longValue());
        comment.setName(user.getName());
        //插入到数据库中
        int insert = commentMapper.insert(comment);
        log.info("CommentServiceImpl.replyComment.comment:{}",comment);
        if (insert>0){
            return Result.success("评论成功");
        }
        return Result.success("评论失败");
    }
}
